var express = require('express')

var user = express.Router()

//引入fs模板
var fs = require('fs')

//引入path模板
var path = require('path')

//注册
user.post('/enroll' , (req,res) => {
    //准备路径
    var filname = path.join(__dirname , '../json.json')
    //读取数据
    var conment = fs.readFileSync(filname)
    conment = conment.toString()? JSON.parse(conment) : []
    var {phone} = req.body
    var index = conment.findIndex((item) => {
        return item.phone == phone
    })
    if(index == -1){
        conment.push({...req.body , isadmin : true , status : true})
        fs.writeFileSync(filname , JSON.stringify( conment ) , 'utf8')
        var new_conment = fs.readFileSync(filname)
        new_conment = new_conment.toString()? JSON.parse(new_conment) : []
        res.send({code : 200 ,list:new_conment })
    }else{
        res.send({code : 400})
    }
     
})



//登录
user.get('/register' ,(req , res) => {
     //准备路径
     var filname = path.join(__dirname , '../json.json')
    //读取数据
    var conment = fs.readFileSync(filname)
    conment = conment.toString()? JSON.parse(conment) : []
    //注册
    var {phone , pass} = req.query
    var i = conment.findIndex((item) => {
        return item.phone == phone && item.pass == pass
    })
    if(i != -1){
        res.send({code:200,mas:'登陆成功'})
    }else{
        res.send({code:400,mas:'用户不存在'})
    }
})

//发送数据库数据
user.get('/list' , (req, res) => {
    //准备路径
    var filname = path.join(__dirname , '../json.json')
    //读取数据
    var conment = fs.readFileSync(filname)
    conment = conment.toString()? JSON.parse(conment) : []
    var {page , count} = req.query
    var new_conment = conment.slice((page - 1) * count , page * count)                                 
    res.send({code:200 , list:new_conment})
})

//删除
user.post('/delete' , (req , res) => {
    //准备路径
    var filname = path.join(__dirname , '../json.json')
    //读取数据
    var conment = fs.readFileSync(filname)
    conment = conment.toString()? JSON.parse(conment) : []
    var {phone} = req.body
    
    // var index = conment.findIndex((item) => {
    //     return item.phone == phone
    // })
    for(var i = 0 ; i < conment.length - 1 ; i++){
        if(conment[i].phone == phone){
            conment.splice(i , 1)
        }
    }

    fs.writeFileSync(filname , JSON.stringify( conment ) , 'utf8')
    res.send({list:conment})

})

module.exports = user;